package com.lh.center.common.web.advice;

import com.lh.center.common.base.ResponseEntity;
import com.lh.center.common.exception.CommonException;
import com.lh.center.common.exception.ErrorEnum;
import com.lh.center.common.web.session.SessionOperation;
import org.apache.dubbo.rpc.RpcException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;

public class DefaultGlobalExceptionAdvice implements GlobalExceptionAdvice{
    @Override
    public boolean printLog(Exception e) {
        if(e instanceof RpcException){
            RpcException ex = (RpcException) e;
            //小于10说明是dubbo自身定义的异常
            if(ex.getCode()>=0 && ex.getCode()<=10){
                return true;
            }
        }
        return !(e instanceof BindException) && !(e instanceof CommonException) && !(e instanceof RpcException);
    }

    @Override
    public Object packageResponse(Exception e) {
        ResponseEntity<?> result = ResponseEntity.error(e.getMessage());
        // 处理dto验证异常
        if (e instanceof BindException) {
            BindException ex = (BindException) e;
            FieldError fieldError = ex.getBindingResult().getFieldError();
            if(fieldError != null){
                result.setErrorMsg(fieldError.getField() + "：" + fieldError.getDefaultMessage());
            }
        }
        // 处理自定义异常
        else if (e instanceof CommonException) {
            CommonException ex = (CommonException) e;
            result.setCode(ex.getErrorCode().getCode());
            result.setErrorMsg(ex.getMessage());
            result.setErrorMsgDesc(ex.getRemark());
        }
        //dubbo异常
        else if(e instanceof RpcException){
            RpcException rex = (RpcException) e;
            result.setCode(rex.getCode());
            result.setErrorMsg(rex.getMessage());
            if(rex.getCode()>=0 && rex.getCode()<=10){
                result.setErrorMsg("远程服务繁忙，请稍后再试");
            }
            //将dubbo原样错误信息返回
            result.setErrorMsgDesc(rex.getMessage());
        }
        else {
            result.setErrorMsg(ErrorEnum.error.getRemark());
            result.setErrorMsgDesc(e.getMessage());
        }
        if(SessionOperation.toTrance.get()!=null && !SessionOperation.toTrance.get()){
            result.setErrorMsgDesc(null);
        }
        return result;
    }
}
